package com.bajiao.service.order.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bajiao.common.constant._Whole;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.common.util.FastJsonHelper;
import com.bajiao.common.util.UUIDGenerator;
import com.bajiao.entity.order.Order;
import com.bajiao.entity.order.RefundCouponOrder;
import com.bajiao.entity.order.RefundOrder;
import com.bajiao.mapper.order.RefundOrderMapper;
import com.bajiao.service.config.ConfigService;
import com.bajiao.service.order.OrderDetailsService;
import com.bajiao.service.order.OrderService;
import com.bajiao.service.order.RefundOrderService;
import com.bajiao.service.user.UserService;
import com.bajiao.third.utils.WxPayUtils;
import com.bajiao.vo.order.OrderDetailsAdmin;
import com.bajiao.vo.order.RefundOrderAdmin;
import com.ijpay.core.kit.WxPayKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 退款单
 * @Author: FanJq
 * @Date:   2024-12-14
 * @Version: V1.0
 */
@Service
public class RefundOrderServiceImpl extends ServiceImpl<RefundOrderMapper, RefundOrder> implements RefundOrderService {

    @Lazy
    @Resource
    private OrderService orderService;
    @Resource
    private UserService userService;
    @Resource
    private ConfigService configService;
    @Resource
    private WxPayUtils wxPayUtils;
    @Resource
    private OrderDetailsService orderDetailsService;

    /**
     * @Description
     * 创建退款单
     * @date 2024/12/19 11:47
     * @author FanJq
     * @param order
     * @return {@link RefundOrder}
    */
    @Override
    public RefundOrder create(Order order, String reason) {
        RefundOrder refundOrder = this.getByOrderNo(order.getOrderNo());
        if (ObjectUtil.isNull(refundOrder)) {
            refundOrder = new RefundOrder();
        }
        refundOrder.setOrderNo(order.getOrderNo());
        refundOrder.setRefundOrderNo(UUIDGenerator.getOrderNoByTime(_Whole.refundOrderNoPrefix));
        refundOrder.setUserId(order.getUserId());
        refundOrder.setStoreId(order.getStoreId());
        refundOrder.setPayPrice(order.getPayPrice());
        refundOrder.setRefundPrice(order.getPayPrice());
        refundOrder.setPayType(order.getPayType());
        refundOrder.setStatus(_Whole.ZERO);
        refundOrder.setReason(reason);
        refundOrder.setOutTradeNo(order.getOutTradeNo());
        super.saveOrUpdate(refundOrder);
        return refundOrder;
    }

    /**
     * @Description
     * 根据主订单编号获取
     * @date 2024/12/19 16:59
     * @author FanJq
     * @param orderNo
     * @return {@link RefundOrder}
    */
    @Override
    public RefundOrder getByOrderNo(String orderNo) {
        return super.lambdaQuery().eq(RefundOrder::getOrderNo, orderNo).one();
    }

    /**
     * @Description
     * 退款单审批
     * @date 2024/12/19 17:14
     * @author FanJq
     * @param refundOrder
     * @param status
     * @return
    */
    @Override
    public void approve(RefundOrder refundOrder, int status) {
        if (refundOrder.getStatus() != _Whole.ZERO)
            return;
        if (status == _Whole.ONE && refundOrder.getRefundPrice().signum() > _Whole.ZERO) {
            //@create by FanJq 2025/1/14 14:30 审核通过
            if (refundOrder.getPayType() == _Whole.ONE) {
                //@create by FanJq 2024/12/19 17:18 更新退款单状态
                refundOrder.setStatus(status);
                super.updateById(refundOrder);
                //@create by FanJq 2024/12/20 14:07 订单执行退款逻辑
                orderService.refundLogic(refundOrder, status);
                //@create by FanJq 2024/12/19 18:13 退款金额入账
                userService.changeMoney(refundOrder.getUserId(), refundOrder.getPayPrice(), _Whole.ONE, refundOrder.getRefundOrderNo(), "商品订单退款", _Whole.FIVE);
            } else if (refundOrder.getPayType() == _Whole.TWO) { //@create by FanJq 2025/1/13 20:07 微信退款
                //@create by FanJq 2024/12/19 17:18 更新退款单状态
                refundOrder.setStatus(_Whole.TWO);
                //String callback = configService.getCallback("wxOrderRefund");
                String callback = "";
                Boolean flag = this.wxPayUtils.refundMoney(refundOrder.getOutTradeNo(), refundOrder.getId(),
                        String.valueOf(refundOrder.getRefundPrice()), String.valueOf(refundOrder.getRefundPrice()), callback);
                if (flag) {
                    //更新退款记录状态和订单项的状态
                    refundOrder.setStatus(_Whole.ONE);
                    //@create by FanJq 2024/12/20 14:07 订单执行退款逻辑
                    orderService.refundLogic(refundOrder, status);
                }
                super.updateById(refundOrder);
            }
        } else {
            //@create by FanJq 2025/1/14 14:30 审核驳回
            refundOrder.setStatus(status);
            super.updateById(refundOrder);
            orderService.refundLogic(refundOrder, status);
        }
    }

    /**
     * @Description
     * 管理后台列表
     * @date 2025/1/8 16:05
     * @author FanJq
     * @param orderNo
     * @param keywords
     * @param productTitle
     * @param status
     * @param createTimeBegin
     * @param createTimeEnd
     * @return {@link List< RefundOrderAdmin>}
    */
    @Override
    public List<RefundOrderAdmin> getAdminList(String orderNo, String keywords, String productTitle, Integer status, String createTimeBegin, String createTimeEnd) {
        if (StrUtil.isAllNotBlank(createTimeBegin, createTimeEnd))
            createTimeEnd = createTimeEnd + " 23:59:59";
        List<RefundOrderAdmin> resultList = super.baseMapper.getAdminList(orderNo, keywords, productTitle, status, createTimeBegin, createTimeEnd);
        resultList.forEach(model -> {
            List<OrderDetailsAdmin> detailsList = new ArrayList<>();
            orderDetailsService.getByOrderNo(model.getOrderNo()).forEach(i-> {
                detailsList.add(FastJsonHelper.beanToBean(i, OrderDetailsAdmin.class));
            });
            model.setOrderDetails(detailsList);
        });
        return resultList;
    }

    /**
     * @Description
     * 微信退款通知
     * @date 2025/1/13 20:26
     * @author FanJq
     * @param request
     * @return
    */
    @Override
    public void refundNotify(HttpServletRequest request) {
        String data = wxPayUtils.refundNotify(request);
        if (StringUtils.isBlank(data)) {
            throw new DataHandleException("解析失败");
        }
        Map<String, String> dataMap = WxPayKit.xmlToMap(data);
        //退款状态
        String refundStatus = dataMap.get("refund_status");
        //退款记录id
        String outRefundNo = dataMap.get("out_refund_no");
        System.out.println("---------退款单号-------" + outRefundNo);
        if (StringUtils.isBlank(outRefundNo)) {
            throw new DataHandleException("商户退款单号为空");
        }
        RefundOrder refundOrder = super.getById(outRefundNo);
        if (ObjectUtil.isNull(refundStatus)) {
            throw new DataHandleException("暂无退款记录");
        }
        //微信可能会通知多次所以需要进行状态判断
        if (refundOrder.getStatus() != _Whole.TWO) {
            return;
        }
        //退款成功
        if (WxPayKit.codeIsOk(refundStatus)) {
            //更新退款记录状态和订单项的状态
            refundOrder.setStatus(_Whole.ONE);
            //@create by FanJq 2024/12/20 14:07 订单执行退款逻辑
            orderService.refundLogic(refundOrder, _Whole.ONE);
        } else {
            //退款失败
            refundOrder.setStatus(_Whole.THREE);
            super.updateById(refundOrder);
            orderService.refundLogic(refundOrder, _Whole.NINE);
        }
    }
}
